package com.example.myapplication;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.example.myapplication.model.Course;
import java.util.List;

public class CourseAdapter extends BaseAdapter {
    private final Context context;
    private final List<Course> courseList;

    public CourseAdapter(Context context, List<Course> courseList) {
        this.context = context;
        this.courseList = courseList;
    }

    @Override
    public int getCount() {
        return courseList.size();
    }

    @Override
    public Object getItem(int position) {
        return courseList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if (convertView == null) {
            convertView = LayoutInflater.from(context).inflate(R.layout.item_course, parent, false);
            holder = new ViewHolder();
            holder.textViewCourseName = convertView.findViewById(R.id.textViewItemCourseName);
            holder.textViewTeacherName = convertView.findViewById(R.id.textViewItemTeacherName);
            holder.textViewAverageRating = convertView.findViewById(R.id.textViewItemAverageRating);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        Course course = courseList.get(position);
        holder.textViewCourseName.setText(course.getName());
        holder.textViewTeacherName.setText(course.getTeacher());

        // 获取课程的平均分并显示
        float averageRating = course.getAverageRating();
        String formattedRating = String.format("%.1f", averageRating);
        holder.textViewAverageRating.setText(formattedRating);

        return convertView;
    }

    static class ViewHolder {
        TextView textViewCourseName;
        TextView textViewTeacherName;
        TextView textViewAverageRating;
    }
}
